//
//  ContactDetailViewController.m
//  cliqset
//
//  Created by David Hinson on 2/11/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "ContactDetailViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"
#import "ContactsViewController.h"
#import "EditPhoneViewController.h"
#import "DetailCell.h"

@implementation ContactDetailViewController

// --- statics
NSString *empty    = @"";
NSString *aPlusStr = @"a+";
NSString *ePlusStr = @"e+";
NSString *iPlusStr = @"i+";
NSString *pPlusStr = @"p+";
NSString *uPlusStr = @"u+";

NSString *addNewAddress = @"Add new Address";
NSString *addNewEmail   = @"Add new Email";
NSString *addNewIM      = @"Add new IM";
NSString *addNewPhone   = @"Add new Phone";
NSString *addNewUrl     = @"Add new URL";

// --- properties

@synthesize index;
@synthesize contactDetailTable;

@synthesize personalPhoneCells;
@synthesize personalEmailCells;
@synthesize personalURLCells;
@synthesize personalIMCells;
@synthesize personalAddressCells;

@synthesize professionalPhoneCells;
@synthesize professionalEmailCells;
@synthesize professionalURLCells;
@synthesize professionalIMCells;
@synthesize professionalAddressCells;

@synthesize addToFavesBtn;
@synthesize editUserBtn;
@synthesize deleteContactBtn;
@synthesize isEditing;
@synthesize isFavorite;
@synthesize isPersonal;
@synthesize myName;
@synthesize myJob;
@synthesize professionalCellsCount;
@synthesize personalCellsCount;

@synthesize bufferContact;

@synthesize viewTimer;

@synthesize header, footer;

@synthesize editButton, saveButton, cancelButton;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

    [super viewDidLoad];
	
	bufferContact = [[Contact alloc] init];
		
	// Dereference our contact
	Contact *contact=nil; 

	//
	// Init data arrays
	//
	personalPhoneCells       = [[NSMutableArray alloc] init];
	personalEmailCells       = [[NSMutableArray alloc] init];
	personalURLCells         = [[NSMutableArray alloc] init];
	personalIMCells          = [[NSMutableArray alloc] init];
	personalAddressCells     = [[NSMutableArray alloc] init];
	professionalPhoneCells   = [[NSMutableArray alloc] init];
	professionalEmailCells   = [[NSMutableArray alloc] init];
	professionalURLCells     = [[NSMutableArray alloc] init];
	professionalIMCells      = [[NSMutableArray alloc] init];
	professionalAddressCells = [[NSMutableArray alloc] init];
	
	if (index >= 0) {
		if (self.isFavorite) {
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
					}
				}
			} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:index];
			}
		
		// Safety valve
		if (contact == nil) {return;}
		
		// Set contact detail
		self.title = [empty stringByAppendingFormat:@"%@ %@", contact.givenName, contact.familyName];
		
		// Set edit button
		editButton = [[[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(doEdit:)] retain];
		self.navigationItem.rightBarButtonItem = editButton;		
		}
	else {		
		self.title = @"Add Contact";
		
		// Set Cancel button
		cancelButton = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(doCancel:)] retain];
		self.navigationItem.leftBarButtonItem = cancelButton;
		
		// Set Save button
		saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleBordered target:self action:@selector(doSave:)] retain];
		self.navigationItem.rightBarButtonItem = saveButton;	
		
		[self resetTimer];
		viewTimer = [[NSTimer timerWithTimeInterval:0.05 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO] retain];
		[[NSRunLoop currentRunLoop] addTimer:viewTimer forMode:NSDefaultRunLoopMode];
	}
	
	[self doTableHeader];	
	[self doTableFooter];
}

-(void)resetTimer {
	[viewTimer invalidate];
	[viewTimer release];
	viewTimer = nil;
}

// We are checking this timer so that we may readjust our viewport.  
- (void)timerFired:(NSTimer *)timer
{
	NSLog(@"Fired");
	[contactDetailTable  setEditing:YES animated:YES];
	self.isEditing = YES;
	[self showEditButton:YES];
	[self showFavesButton:NO];
	
	self.contactDetailTable.allowsSelectionDuringEditing = YES;
	[self.contactDetailTable reloadData];
}

// Do cancel
-(void)doCancel:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSLog(@"Do Cancel");
	[myApp slideContactOut];
}

// Do save
-(void)doSave:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSLog(@"Do Save");
	[myApp.cliqset putContact:bufferContact];
	[myApp slideContactOut];
	[myApp reloadContactsTable];
}

- (void)viewWillAppear:(BOOL)animated {
    [self.contactDetailTable reloadData];
}

// Process menu button clicks
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
		
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	// Dereference our contact
	Contact *contact=nil; 
	if (self.isFavorite) {
		for (int x=0; x<[myApp.contacts count]; x++) {
			Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
				contact = localContact;
				break;
			}
		}
	} 
	else {
		contact = (Contact *)[myApp.contacts objectAtIndex:index];
	}
	
	switch (buttonIndex) {
		case 0:			
			// Delete the contact
			[myApp.cliqset deleteUserContact:contact.contactIdentifier isFavorite:self.isFavorite];
						
			break;
		default:
			break;
	}
}

// Delete the contact
-(void)deleteContact:(id)id {
	
	UIActionSheet* myAction = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	
	[myAction addButtonWithTitle:@"Delete Contact"];
	[myAction addButtonWithTitle:@"Cancel"];
	
	myAction.destructiveButtonIndex=0;
	myAction.cancelButtonIndex=1;
		
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	[myAction showInView:[myApp window]];
	
	[myAction release];
}

// Create Table Footer
-(void)doTableFooter {
	
	// If this is a new contact, suppress delete contact button
	if (index < 0) {return;}
	
	self.footer = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 80.0)] retain];

	self.deleteContactBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	self.deleteContactBtn.frame = CGRectMake(10.0, 10.0, 300.0, 40.0);
	[self.deleteContactBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
	
	[self.deleteContactBtn addTarget:self action:@selector(deleteContact:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *img = [UIImage imageNamed:@"delete-contact-with-text.png" ] ;
	[self.deleteContactBtn setBackgroundImage:img forState:UIControlStateNormal];
	
	self.deleteContactBtn.alpha = 0.0;
	[self.footer addSubview:self.deleteContactBtn];
	
	self.contactDetailTable.tableFooterView = self.footer;
}

// Create Table Header
-(void)doTableHeader {
		
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	Contact *contact=nil; 
	Contact *temp = [[Contact alloc] init];
	
	if (self.index >= 0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:self.index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	} else {
		contact = temp;
		contact.givenName  = @"First";
		contact.familyName = @"Last";
		contact.company    = @"Company";
	}
	
	NSData* imageData;
	UIImage * graphic;
	UIImageView *showImage;
	
	self.header    = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 90)] retain];
	UIColor* textColor = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	// Fonts for Labels
	UIFont* teeny_font      = [UIFont systemFontOfSize:14];
	UIFont* bold_large_font = [UIFont boldSystemFontOfSize:18];

	// Grab image from the web (for now)
	
	if (self.index>=0) {
		imageData = contact.photoBlob;
		graphic = (UIImage*)[[UIImage alloc] initWithData:imageData];
	} else {
		graphic = [UIImage imageNamed:@"Dummy.png"];
	}
	
	// Allocate image
	showImage        = [[UIImageView alloc] initWithFrame:CGRectMake(230.0, 10.0, 80.0, 80.0 * (graphic.size.height / graphic.size.width))];
	showImage.opaque = NO;    
	showImage.image  = graphic;
	
	UIView * imageBackground  = [[UIView alloc] init];
	CGRect adjFrame           = showImage.frame;
	adjFrame.origin.x--;
	adjFrame.origin.y--;
	adjFrame.size.height+=2;
	adjFrame.size.width+=2;
	imageBackground.backgroundColor = [UIColor grayColor];
	imageBackground.frame     = adjFrame;
	[self.header addSubview:imageBackground];
	[imageBackground release];
	
	// Add picture to the cell
	[self.header addSubview:showImage];

	[showImage release];
	[graphic release];
	
	// Allocate Labels
	myName = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 190.0, 20.0)] retain];
	myJob  = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 30.0, 190.0, 20.0)] retain];

	self.editUserBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
	self.editUserBtn.frame = CGRectMake(5.0, 5.0, 220.0, 85.0);
	[self.editUserBtn setTitleColor:textColor forState:UIControlStateNormal];
	[self.editUserBtn addTarget:self action:@selector(doUserEdit:) forControlEvents:UIControlEventTouchUpInside];
	[self.editUserBtn setBackgroundImage:[UIImage imageNamed:@"not-selected.png"] forState:UIControlStateNormal];
	[self.editUserBtn setBackgroundImage:[UIImage imageNamed:@"selected-alpha.png"] forState:UIControlStateSelected];
	
	self.editUserBtn.alpha  = 0;
	
	[header addSubview:self.editUserBtn];
	
	self.addToFavesBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
	self.addToFavesBtn.frame = CGRectMake(10.0, 60.0, 150.0, 30.0);
	[self.addToFavesBtn setTitleColor:textColor forState:UIControlStateNormal];
	
	[self.addToFavesBtn addTarget:self action:@selector(addToFaves:) forControlEvents:UIControlEventTouchUpInside];
	
	// Add button action
	if ([myApp.database isContactAFavorite:myApp.userString cid:contact.contactIdentifier]) {
		self.addToFavesBtn.tag = 1;
		[self.addToFavesBtn setTitle:@"Remove Favorite" forState:UIControlStateNormal];
	} else {
		self.addToFavesBtn.tag = 0;
		[self.addToFavesBtn setTitle:@"Add to Favorites" forState:UIControlStateNormal];
	}
	
	// Don't display if this is a favorite
	if (self.isFavorite) {
		self.addToFavesBtn.hidden = YES;
	}
	// Don't display if this is an add
	if (self.index < 0) {
		self.addToFavesBtn.hidden = YES;
	}
	
	// Add button to the cell
	[header addSubview:addToFavesBtn];
	
	// Set name label
	myName.text = [empty stringByAppendingFormat:@"%@ %@", contact.givenName, contact.familyName];
	myName.font = bold_large_font;
	
	// Set job label
	myJob.text  = contact.company;
	myJob.font  = teeny_font;
	
	// Set label background color
	myName.backgroundColor = [UIColor clearColor];
	myJob.backgroundColor  = [UIColor clearColor];
	
	// Set text color
	myName.textColor       = textColor;
	myJob.textColor        = textColor;
	
	// Add labels to the cell
	[header addSubview:myName];
	[header addSubview:myJob];
	
	self.isEditing = NO;
	
	self.contactDetailTable.tableHeaderView = header;
	
	[temp release];
}

- (void)showFavesButton:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		self.addToFavesBtn.alpha = 1.0;
	}
	else
	{
		self.addToFavesBtn.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

- (void)showEditButton:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		self.editUserBtn.alpha  = 1.0;
	}
	else
	{
		self.editUserBtn.alpha  = 0.0;
	}
	
	[UIView commitAnimations];
}

- (void)showDeleteContactButton:(BOOL)show
{
	// fade animate the view out of view by affecting its alpha
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.40];
    
	if (show)
	{
		self.deleteContactBtn.alpha = 1.0;
	}
	else
	{
		self.deleteContactBtn.alpha = 0.0;
	}
	
	[UIView commitAnimations];
}

// Start editing
-(void)doEdit:(id)id {
	UIBarButtonItem* btn = (UIBarButtonItem*)id;
	
	if ([btn.title isEqualToString:@"Edit"]) {
		[self setEditing:YES animated:YES];
		btn.title                    = @"Done";
		self.isEditing               = YES;
		[self showEditButton:YES];
		[self showDeleteContactButton:YES];
		[self showFavesButton:NO];
	} else {
		[self setEditing:NO animated:YES];
		btn.title                    = @"Edit";
		self.isEditing               = NO;
		[self showEditButton:NO];
		[self showDeleteContactButton:NO];
		[self showFavesButton:YES];
	}
	
	self.contactDetailTable.allowsSelectionDuringEditing = YES;
	[self.contactDetailTable reloadData];
}

// Perform user edit
-(void)doUserEdit:(id)id {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	Contact *contact=nil; 
	if (self.index >=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:self.index]]) {
					contact = localContact;
					break;
					}
				}
		} 
	else {
		contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	} else {
		contact = self.bufferContact;
		}

	// Slide user screen in
	[myApp slideUserIn:self givenName:contact.givenName familyName:contact.familyName position:contact.position company:contact.company];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

#pragma mark ---- table handling ----

// Load all contact sections
-(void)loadAllSections {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	Contact *contact=nil; 
	
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:self.index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	} 
	else {
		contact = bufferContact;
	}
	
	NSMutableString *content;
	
	//
	// Reset data arrays
	//
	
	// Reset content
	if (personalPhoneCells && @selector(personalPhoneCells) && [personalPhoneCells count]) {[personalPhoneCells removeAllObjects];}
	if (personalEmailCells && @selector(personalEmailCells) && [personalEmailCells count]) {[personalEmailCells removeAllObjects];}
	if (personalURLCells && @selector(personalURLCells) && [personalURLCells count]) {[personalURLCells removeAllObjects];}
	if (personalIMCells && @selector(personalIMCells) && [personalIMCells count]) {[personalIMCells removeAllObjects];}
	if (personalAddressCells && @selector(personalAddressCells) && [personalAddressCells count]) {[personalAddressCells removeAllObjects];}
	if (professionalPhoneCells && @selector(professionalPhoneCells) && [professionalPhoneCells count]) {[professionalPhoneCells removeAllObjects];}
	if (professionalEmailCells && @selector(professionalEmailCells) && [professionalEmailCells count]) {[professionalEmailCells removeAllObjects];}
	if (professionalURLCells && @selector(professionalURLCells) && [professionalURLCells count]) {[professionalURLCells removeAllObjects];}
	if (professionalIMCells && @selector(professionalIMCells) && [professionalIMCells count]) {[professionalIMCells removeAllObjects];}
	if (professionalAddressCells && @selector(professionalAddressCells) && [professionalAddressCells count]) {[professionalAddressCells removeAllObjects];}
	
	// Phones
	for (int x=0; x < [contact.phones count]; x++) {
		Phone *phone = (Phone *)[contact.phones objectAtIndex:x];
		if ([phone.type isEqualToString:@"Personal"] && [phone.phoneNumber length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Home";
			cell.content = phone.phoneNumber;
			cell.type    = @"p";
			cell.tag     = 1;
			cell.elementIndex = x;
			[personalPhoneCells addObject:cell];
			[cell release];
		}
		if ([phone.type isEqualToString:@"PersonalFax"] && [phone.phoneNumber length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Fax";
			cell.content = phone.phoneNumber;
			[personalPhoneCells addObject:cell];
			cell.type    = @"p";
			cell.tag     = 2;
			cell.elementIndex = x;
			[cell release];
		}
		if ([phone.type isEqualToString:@"PersonalMobile"] && [phone.phoneNumber length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Mobile";
			cell.type    = @"p";
			cell.tag     = 3;
			cell.elementIndex = x;
			cell.content = phone.phoneNumber;
			[personalPhoneCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new phone
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewPhone;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)pPlusStr;
		cell.tag = -1;
		[personalPhoneCells addObject:cell];
		[cell release];
	}

	// Email Addresses
	for (int x=0; x < [contact.emailAddresses count]; x++) {
		EmailAddress *email = (EmailAddress *)[contact.emailAddresses objectAtIndex:x];
		if ([email.type isEqualToString:@"Personal"] && [email.address length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Email";
			cell.content = email.address;
			cell.type    = @"e";
			cell.tag     = (60+x);
			cell.elementIndex = x;
			[personalEmailCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new email address
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewEmail;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)ePlusStr;
		cell.tag     = -2;
		[personalEmailCells addObject:cell];
		[cell release];
	}
	
	// URLs
	for (int x=0; x < [contact.urls count]; x++) {
		URL *url = (URL *)[contact.urls objectAtIndex:x];
		if ([url.type isEqualToString:@"PersonalBlog"] && [url.url length] > 0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Blog";
			cell.content = url.url;
			cell.type    = @"u";
			cell.tag     = 6;
			cell.elementIndex = x;
			[personalURLCells addObject:cell];
			[cell release];
		}
		if ([url.type isEqualToString:@"PersonalWebsite"] && [url.url length] > 0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Website";
			cell.content = url.url;
			cell.type    = @"u";
			cell.tag     = 7;
			cell.elementIndex = x;
			[personalURLCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new URL
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewUrl;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)uPlusStr;
		cell.tag     = -5;
		[personalURLCells addObject:cell];
		[cell release];
	}

	for (int x=0; x < [contact.imScreenNames count]; x++) {
		IM *im = (IM *)[contact.imScreenNames objectAtIndex:x];
		ContactCell *cell = [[ContactCell alloc] init];
		NSRange personalRange = [im.network rangeOfString:@"Personal" options: NSCaseInsensitiveSearch];
		if (personalRange.location != NSNotFound) {
			cell.label   = (NSMutableString*)[im.network stringByReplacingOccurrencesOfString:@"Personal" withString:empty];
			cell.content = im.name;
			cell.type    = @"i";
			cell.tag     = (8+x);
			cell.elementIndex = x;
			[personalIMCells addObject:cell];
		}
		[cell release];
	}
	
	// Add new IM
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewIM;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)iPlusStr;
		cell.tag     = -4;
		[personalIMCells addObject:cell];
		[cell release];
	}

	// Street Addresses
	for (int x=0; x < [contact.addresses count]; x++) {
		Address *address = (Address *)[contact.addresses objectAtIndex:x];
		if ([address.type isEqualToString:@"Home"] && [address.streetAddress length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Home";
			content      = (NSMutableString*)[empty stringByAppendingFormat:@"%@\r\n%@ %@  %@\r\n%@", address.streetAddress, address.locality, address.region, address.postalCode, address.country];
			cell.content = content;
			cell.type    = @"a";
			cell.tag     = (50+x);
			cell.elementIndex = x;
			[personalAddressCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new address
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewAddress;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)aPlusStr;
		cell.tag     = -3;
		[personalAddressCells addObject:cell];
		[cell release];
	}

	// Phones
	for (int x=0; x < [contact.phones count]; x++) {
		Phone *phone = (Phone *)[contact.phones objectAtIndex:x];
		if ([phone.type isEqualToString:@"Work"] && [phone.phoneNumber length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Office";
			cell.content = phone.phoneNumber;
			cell.type    = @"p";
			cell.tag     = 101;
			cell.elementIndex = x;
			[professionalPhoneCells addObject:cell];
			[cell release];
		}
		if ([phone.type isEqualToString:@"WorkFax"] && [phone.phoneNumber length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Fax";
			cell.content = phone.phoneNumber;
			cell.type    = @"p";
			cell.tag     = 102;
			cell.elementIndex = x;
			[professionalPhoneCells addObject:cell];
			[cell release];
		}
		if ([phone.type isEqualToString:@"WorkMobile"] && [phone.phoneNumber length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Mobile";
			cell.content = phone.phoneNumber;
			cell.type    = @"p";
			cell.tag     = 103;
			cell.elementIndex = x;
			[professionalPhoneCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new phone
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewPhone;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)pPlusStr;
		cell.tag     = (-101);
		[professionalPhoneCells addObject:cell];
		[cell release];
	}
	
	// Email Addresses
	for (int x=0; x < [contact.emailAddresses count]; x++) {
		EmailAddress *email = (EmailAddress *)[contact.emailAddresses objectAtIndex:x];
		if ([email.type isEqualToString:@"Work"] && [email.address length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Email";
			cell.content = email.address;
			cell.type    = @"e";
			cell.tag     = 105;
			cell.elementIndex = x;
			[professionalEmailCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new email address
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewEmail;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)ePlusStr;
		cell.tag = -102;
		[professionalEmailCells addObject:cell];
		[cell release];
	}

	// URLs
	for (int x=0; x < [contact.urls count]; x++) {
		URL *url = (URL *)[contact.urls objectAtIndex:x];
		if ([url.type isEqualToString:@"WorkBlog"] && [url.url length] > 0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Blog";
			cell.content = url.url;
			cell.type    = @"u";
			cell.tag     = 106;
			cell.elementIndex = x;
			[professionalURLCells addObject:cell];
			[cell release];
		}
		if ([url.type isEqualToString:@"WorkWebsite"] && [url.url length] > 0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Website";
			cell.content = url.url;
			cell.type    = @"u";
			cell.tag     = 107;
			cell.elementIndex = x;
			[professionalURLCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new URL
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewUrl;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)uPlusStr;
		cell.tag = -105;
		[professionalURLCells addObject:cell];
		[cell release];
	}

	for (int x=0; x < [contact.imScreenNames count]; x++) {
		IM *im = (IM *)[contact.imScreenNames objectAtIndex:x];
		ContactCell *cell = [[ContactCell alloc] init];
		NSRange workRange = [im.network rangeOfString:@"Work" options: NSCaseInsensitiveSearch];
		if (workRange.location != NSNotFound) {
			cell.label   = (NSMutableString*)[im.network stringByReplacingOccurrencesOfString:@"Work" withString:empty];
			cell.content = im.name;
			cell.type    = @"i";
			cell.tag     = (108 + x);
			cell.elementIndex = x;
			[professionalIMCells addObject:cell];
		}
		[cell release];
	}
	
	// Add new IM
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewIM;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)iPlusStr;
		cell.tag     = -104;
		[professionalIMCells addObject:cell];
		[cell release];
	}
	
	// Street Addresses
	for (int x=0; x < [contact.addresses count]; x++) {
		Address *address = (Address *)[contact.addresses objectAtIndex:x];
		if ([address.type isEqualToString:@"Work"] && [address.streetAddress length]>0) {
			ContactCell *cell = [[ContactCell alloc] init];
			cell.label   = @"Work";
			content      = (NSMutableString*)[empty stringByAppendingFormat:@"%@\r\n%@ %@  %@\r\n%@", address.streetAddress, address.locality, address.region, address.postalCode, address.country];
			cell.content = content;
			cell.type    = @"a";
			cell.tag     = (150 + x);
			cell.elementIndex = x;
			[professionalAddressCells addObject:cell];
			[cell release];
		}
	}
	
	// Add new address
	{
		ContactCell *cell = [[ContactCell alloc] init];
		cell.label   = (NSMutableString*)addNewAddress;
		cell.content = (NSMutableString*)empty;
		cell.type    = (NSMutableString*)aPlusStr;
		cell.tag     = -103;
		[professionalAddressCells addObject:cell];
		[cell release];
	}
	
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	
	tableView.backgroundColor = [UIColor clearColor];

	// OK... load up our sections
	[self loadAllSections];
	
	return 10;
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

	switch (indexPath.section) {
		case 0:
		case 1:			
		case 2:			
		case 3:
			if ([self sectionCount:indexPath.section] > 0) {
				return 44.0;
				}
			else {
				return 0;
				}
			break;
		case 4:
			if ([self sectionCount:indexPath.section] > 0) {
				return 70.0;
			} else {
				return 0;
				}
			break;
			
		case 5:
		case 6:
		case 7:
		case 8:
			if ([self sectionCount:indexPath.section] > 0) {
				return 44.0;
			}
			else {
				return 0;
			}
			break;
		case 9:
			if ([self sectionCount:indexPath.section] > 0) {
				return 70.0;
			} else {
				return 0;
			}
			break;
		default:
			return 0;
			break;
		}
}

// Set Section Header Height
- (CGFloat)tableView:(UITableView *)aTableView heightForHeaderInSection:(NSInteger)section{
	
	if (section > 9) {return 0;}
	
	if (section == 0 || section == 5) {
		return 41;
		}
	
	if (section > 5) {
		int count = 0;
		for (int x=section-1; x>=5; x--) {
			count += [self sectionCount:x];
			}
		if (count>0) {
			return 7;
		}
		else {
			return 0;
		}
	} else {
		int count = 0;
		for (int x=section-1; x>=0; x--) {
			count += [self sectionCount:x];
		}
		if (count>0) {
			return 7;
		}
		else {
			return 0;
		}
	}
}

// Header section view
- (NSString *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	
	UIView *smallView           = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 1.0)] retain];
	UIView *headerView           = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)] retain];
	
    UIColor* myGray              = [UIColor colorWithRed:132.0/255.0 green:132.0/255.0 blue:132.0/255.0 alpha:1.0];	
    UILabel* sectionTitle        = [[UILabel alloc] initWithFrame:CGRectMake(9.0, 5.0, 302.0, 30.0)];
	
    sectionTitle.textColor       = [UIColor whiteColor];
    sectionTitle.textAlignment   = UITextAlignmentLeft;
    sectionTitle.backgroundColor = myGray;
    sectionTitle.font            = [UIFont boldSystemFontOfSize:20];
	
    switch (section) {
        case 0:
			sectionTitle.text = @"  Personal Infomation";
			if (!tableView.isEditing) {
				if (([self.personalPhoneCells count] + [self.personalEmailCells count] + [self.personalURLCells count] + [self.personalIMCells count] + [self.personalAddressCells count]) == 5) {
					return nil;
					}
				}
			break;
		case 1:
		case 2:
		case 3:
		case 4:
			if ([self sectionCount:section]>0) {
				return (NSString*)smallView;
			}
			return nil;
			break;
        case 5:
			sectionTitle.text = @"  Professional Infomation";
			if (!tableView.isEditing) {
				if (([self.professionalPhoneCells count] + [self.professionalEmailCells count] + [self.professionalURLCells count] + [self.professionalIMCells count] + [self.professionalAddressCells count]) == 5) {
					return nil;
				}
			}
            break;
		case 6:
		case 7:
		case 8:
		case 9:
			if ([self sectionCount:section]>0) {
				return (NSString*)smallView;
			}
			return nil;
			break;
        default:
			return nil;
            break;
    }
	
	[headerView addSubview:sectionTitle];	
	[sectionTitle release];
	
    return (NSString *)headerView;
}

// Count cells in a section
-(int)sectionCount:(int)section {

	int count = 0;
	
	switch (section) {
		case 0:
			count = [self.personalPhoneCells count];
			break;
		case 1:
			count = [self.personalEmailCells count];
			break;
		case 2:
			count = [self.personalURLCells count];
			break;
		case 3:
			count = [self.personalIMCells count];
			break;
		case 4:
			count = [self.personalAddressCells count];
			break;
		case 5:
			count = [self.professionalPhoneCells count];
			break;
		case 6:
			count = [self.professionalEmailCells count];
			break;
		case 7:
			count = [self.professionalURLCells count];
			break;
		case 8:
			count = [self.professionalIMCells count];
			break;
		case 9:
			count = [self.professionalAddressCells count];
			break;
			
	}
		
    if (self.contactDetailTable.editing) {return count;}
	return count-1;
}

// Return rows in table section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {	
	return [self sectionCount:section];
}

// Add to faves
-(void)addToFaves:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
			}
		}	
	else {
		contact = bufferContact;
		}
	
	if (self.addToFavesBtn.tag == 0) {
		NSLog(@"addToFaves");
		[myApp.database addFavorite:myApp.userString cid:contact.contactIdentifier];
		[self.addToFavesBtn setTitle:@"Remove Favorite" forState:UIControlStateNormal];
		self.addToFavesBtn.tag = 1;
	} else {
		NSLog(@"removeFromFaves");
		[myApp.database removeFavorite:myApp.userString cid:contact.contactIdentifier];
		[self.addToFavesBtn setTitle:@"Add To Favorites" forState:UIControlStateNormal];
		self.addToFavesBtn.tag = 0;
		}
	
	// Reload database
	[myApp.database loadFavorites:myApp.userString];
	
	// Reload favorites table in memory
	if (!self.isFavorite) {
		[myApp reloadFavoritesTable];
		}
}

// Indicate disclosure
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	ContactCell *cell;
	
	if (tableView.isEditing) {
		switch (indexPath.section) {
			case 0:
				
				if (indexPath.row >= [self.personalPhoneCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.personalPhoneCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 1:
				
				if (indexPath.row >= [self.personalEmailCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.personalEmailCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 2:
				
				if (indexPath.row >= [self.personalURLCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.personalURLCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 3:
				
				if (indexPath.row >= [self.personalIMCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.personalIMCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 4:
				
				if (indexPath.row >= [self.personalAddressCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.personalAddressCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 5:
				
				if (indexPath.row >= [self.professionalPhoneCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.professionalPhoneCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 6:
				
				if (indexPath.row >= [self.professionalEmailCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.professionalEmailCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 7:
				
				if (indexPath.row >= [self.professionalURLCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.professionalURLCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 8:
				
				if (indexPath.row >= [self.professionalIMCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.professionalIMCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
			case 9:
				
				if (indexPath.row >= [self.professionalAddressCells count]) {return UITableViewCellAccessoryNone;}
				
				cell = (ContactCell*)[self.professionalAddressCells objectAtIndex:indexPath.row];
				if ([cell.type isEqualToString:empty]) return UITableViewCellAccessoryNone;
				break;
		}
		return UITableViewCellAccessoryDisclosureIndicator;	
		} 
	else {
		return UITableViewCellAccessoryNone;
	}
}
// *******************************
//
// Draw the cell
//
// ********************************
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    DetailCell *cell = (DetailCell *)[tableView dequeueReusableCellWithIdentifier:@"DetailCell"];
    if (cell == nil) {
        cell = [[[DetailCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"DetailCell"] autorelease];
        cell.hidesAccessoryWhenEditing = NO;
    }

	ContactCell *deref;
	int compareCount;
	
	switch (indexPath.section) {
		case 0:
			compareCount = [self.personalPhoneCells count];
			deref        = (ContactCell*)[self.personalPhoneCells objectAtIndex:indexPath.row];
			break;
		case 1:
			compareCount = [self.personalEmailCells count];
			deref        = (ContactCell*)[self.personalEmailCells objectAtIndex:indexPath.row];
			break;
		case 2:
			compareCount = [self.personalURLCells count];
			deref        = (ContactCell*)[self.personalURLCells objectAtIndex:indexPath.row];
			break;
		case 3:
			compareCount = [self.personalIMCells count];
			deref        = (ContactCell*)[self.personalIMCells objectAtIndex:indexPath.row];
			break;
		case 4:
			compareCount = [self.personalAddressCells count];
			deref        = (ContactCell*)[self.personalAddressCells objectAtIndex:indexPath.row];
			break;
		case 5:
			compareCount = [self.professionalPhoneCells count];
			deref        = (ContactCell*)[self.professionalPhoneCells objectAtIndex:indexPath.row];
			break;
		case 6:
			compareCount = [self.professionalEmailCells count];
			deref        = (ContactCell*)[self.professionalEmailCells objectAtIndex:indexPath.row];
			break;
		case 7:
			compareCount = [self.professionalURLCells count];
			deref        = (ContactCell*)[self.professionalURLCells objectAtIndex:indexPath.row];
			break;
		case 8:
			compareCount = [self.professionalIMCells count];
			deref        = (ContactCell*)[self.professionalIMCells objectAtIndex:indexPath.row];
			break;
		case 9:
			compareCount = [self.professionalAddressCells count];
			deref        = (ContactCell*)[self.professionalAddressCells objectAtIndex:indexPath.row];
			break;
	}

	cell.tag = deref.tag;
	
	if (indexPath.row < compareCount) {
		if (tableView.isEditing && ([deref.type isEqualToString:aPlusStr] || [deref.type isEqualToString:pPlusStr] || [deref.type isEqualToString:ePlusStr] || [deref.type isEqualToString:iPlusStr] || [deref.type isEqualToString:uPlusStr])) {
			cell.prompt.text = [NSString stringWithFormat:@"%@", deref.label];
			cell.promptMode = YES;
		} else {
			cell.type.text = deref.label;
			cell.name.text = deref.content;
			cell.promptMode = NO;
			}
		} 
	
	//UIColor* myBGColor               = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	//cell.contentView.backgroundColor = myBGColor;
	for ( UIView* view in cell.contentView.subviews ) 
	{
		view.backgroundColor = [ UIColor clearColor ];
	}
	
    return cell;
}

// Launch app based upon tagged cell
-(void)launchApp:(int)tag {
	
	// See if this is in a personal phone cell
	for (int x=0; x<[personalPhoneCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalPhoneCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"p"]) {
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@" " withString:@"-"];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@"(" withString:empty];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@")" withString:empty];
				NSString *urlString = [empty stringByAppendingFormat:@"tel:%@", cell.content];
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
				}
			}
		}
	
	// See if this is in a personal email cell
	for (int x=0; x<[personalEmailCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalEmailCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"e"]) {
				NSString * urlString = [empty stringByAppendingFormat:@"mailto:%@?subject=cliqset", cell.content];
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
				}
			}
		}
	
	// See if this is in a personal URL
	for (int x=0; x<[personalURLCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalURLCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"u"]) {
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:cell.content]];
			}
		}
	}
	
// ----
	
	// See if this is in a professional phone cell
	for (int x=0; x<[professionalPhoneCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalPhoneCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"p"]) {
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@" " withString:@"-"];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@"(" withString:empty];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@")" withString:empty];
				NSString *urlString = [empty stringByAppendingFormat:@"tel:%@", cell.content];
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
			}
		}
	}
	
	// See if this is in a professional email cell
	for (int x=0; x<[professionalEmailCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalEmailCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"e"]) {
				NSString * urlString = [empty stringByAppendingFormat:@"mailto:%@?subject=cliqset", cell.content];
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
			}
		}
	}
	
	// See if this is in a professional URL
	for (int x=0; x<[professionalURLCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalURLCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"u"]) {
				[[UIApplication sharedApplication] openURL:[NSURL URLWithString:cell.content]];
			}
		}
	}
	
}

// Drill down an edit
-(void)drillDownAndEdit:(int)tag {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	// See if this is in a personal phone cell
	for (int x=0; x<[personalPhoneCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalPhoneCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"p"]) {
				self.isPersonal = YES;
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@" " withString:@"-"];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@"(" withString:empty];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@")" withString:empty];
				[myApp slidePhoneIn:self label:cell.label content:cell.content];
			}
			if ([cell.type isEqualToString:pPlusStr]) {
				self.isPersonal = YES;
				[myApp slidePhoneIn:self label:@"home" content:empty];
			}

		}
	}

	// See if this is in a personal email cell
	for (int x=0; x<[personalEmailCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalEmailCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"e"]) {
				self.isPersonal = YES;
				[myApp slideEmailIn:self label:@"personal" content:cell.content];
			}
			if ([cell.type isEqualToString:ePlusStr]) {
				self.isPersonal = YES;
				[myApp slideEmailIn:self label:@"personal" content:empty];
			}
		}
	}

	// See if this is in a personal url cell
	for (int x=0; x<[personalURLCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalURLCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"u"]) {
				self.isPersonal = YES;
				[myApp slideURLIn:self label:cell.label content:cell.content];
			}
			if ([cell.type isEqualToString:uPlusStr]) {
				self.isPersonal = YES;
				[myApp slideURLIn:self label:@"blog" content:empty];
			}
		}
	}
	
	// See if this is in a personal im cell
	for (int x=0; x<[personalIMCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalIMCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"i"]) {
				self.isPersonal = YES;
				[myApp slideIMIn:self label:cell.label content:cell.content];
			}
			if ([cell.type isEqualToString:iPlusStr]) {
				self.isPersonal = YES;
				[myApp slideIMIn:self label:@"aim" content:empty];
			}
		}
	}
	
	// See if this is in a personal address cell
	for (int x=0; x<[personalAddressCells count]; x++) {
		ContactCell * cell = (ContactCell*)[personalAddressCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"a"]) {
				self.isPersonal = YES;
				
				Address* address = [contact.addresses objectAtIndex:cell.elementIndex];
				
				[myApp slideAddressIn:self label:cell.label street:address.streetAddress locality:address.locality region:address.region postalCode:address.postalCode country:address.country];
			}
			if ([cell.type isEqualToString:aPlusStr]) {
				self.isPersonal = YES;
				[myApp slideAddressIn:self label:cell.label street:empty locality:empty region:empty postalCode:empty country:empty];
			}
		}
	}
	
// ----
	
	// See if this is in a professional phone cell
	for (int x=0; x<[professionalPhoneCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalPhoneCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"p"]) {
				self.isPersonal = NO;
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@" " withString:@"-"];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@"(" withString:empty];
				cell.content = (NSMutableString*)[cell.content stringByReplacingOccurrencesOfString:@")" withString:empty];
				[myApp slidePhoneIn:self label:cell.label content:cell.content];
			}
			if ([cell.type isEqualToString:pPlusStr]) {
				self.isPersonal = NO;
				[myApp slidePhoneIn:self label:@"office" content:empty];
			}
			
		}
	}
	
	// See if this is in a professional email cell
	for (int x=0; x<[professionalEmailCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalEmailCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"e"]) {
				self.isPersonal = NO;
				[myApp slideEmailIn:self label:@"work" content:cell.content];
			}
			if ([cell.type isEqualToString:ePlusStr]) {
				self.isPersonal = NO;
				[myApp slideEmailIn:self label:@"work" content:empty];
			}
		}
	}
	
	// See if this is in a professional url cell
	for (int x=0; x<[professionalURLCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalURLCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"u"]) {
				self.isPersonal = NO;
				[myApp slideURLIn:self label:cell.label content:cell.content];
			}
			if ([cell.type isEqualToString:uPlusStr]) {
				self.isPersonal = NO;
				[myApp slideURLIn:self label:@"blog" content:empty];
			}
		}
	}
	
	// See if this is in a personal im cell
	for (int x=0; x<[professionalIMCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalIMCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"i"]) {
				self.isPersonal = NO;
				[myApp slideIMIn:self label:cell.label content:cell.content];
			}
			if ([cell.type isEqualToString:iPlusStr]) {
				self.isPersonal = NO;
				[myApp slideIMIn:self label:@"aim" content:empty];
			}
		}
	}
	
	// See if this is in a personal address cell
	for (int x=0; x<[professionalAddressCells count]; x++) {
		ContactCell * cell = (ContactCell*)[professionalAddressCells objectAtIndex:x];
		if (cell.tag == tag) {
			if ([cell.type isEqualToString:@"a"]) {
				self.isPersonal = NO;
				
				Address* address = [contact.addresses objectAtIndex:cell.elementIndex];
				
				[myApp slideAddressIn:self label:cell.label street:address.streetAddress locality:address.locality region:address.region postalCode:address.postalCode country:address.country];
			}
			if ([cell.type isEqualToString:aPlusStr]) {
				self.isPersonal = NO;
				[myApp slideAddressIn:self label:cell.label street:empty locality:empty region:empty postalCode:empty country:empty];
			}
		}
	}
	
}

// Row selected... either launch Phone, Email, or Browser (if not editing)... or drill down and edit element.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    //[hitCell setSelected:NO animated:YES];
	
	if (!tableView.isEditing) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
		//[self drillDownAndEdit:tableView indexPath:indexPath];
		[self launchApp:hitCell.tag];
		}
	else {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
		[self drillDownAndEdit:hitCell.tag];
		}
}

// The editing style for a row is the kind of button displayed to the left of the cell when in editing mode.
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.editing == NO || !indexPath) return UITableViewCellEditingStyleNone;

	ContactCell * cell;
	switch (indexPath.section) {
		case 0:
			
			if (indexPath.row >= [self.personalPhoneCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.personalPhoneCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 1:

			if (indexPath.row >= [self.personalEmailCells count]) {return UITableViewCellEditingStyleInsert;}

			cell = [self.personalEmailCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 2:

			if (indexPath.row >= [self.personalURLCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.personalURLCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 3:

			if (indexPath.row >= [self.personalIMCells count]) {return UITableViewCellEditingStyleInsert;}

			cell = [self.personalIMCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 4:
			
			if (indexPath.row >= [self.personalAddressCells count]) {return UITableViewCellEditingStyleInsert;}
					
			cell = [self.personalAddressCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 5:
			
			if (indexPath.row >= [self.professionalPhoneCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.professionalPhoneCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
				}
			break;
		case 6:
			
			if (indexPath.row >= [self.professionalEmailCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.professionalEmailCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 7:
			
			if (indexPath.row >= [self.professionalURLCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.professionalURLCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 8:
			
			if (indexPath.row >= [self.professionalIMCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.professionalIMCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		case 9:
			
			if (indexPath.row >= [self.professionalAddressCells count]) {return UITableViewCellEditingStyleInsert;}
			
			cell = [self.professionalAddressCells objectAtIndex:indexPath.row];
			if ([cell.type isEqualToString:aPlusStr] || [cell.type isEqualToString:pPlusStr] || [cell.type isEqualToString:ePlusStr] || [cell.type isEqualToString:iPlusStr] || [cell.type isEqualToString:uPlusStr]) {
                return UITableViewCellEditingStyleInsert;
			}
			break;
		default:
			break;
	}
	
	// Account for our dummy cell at the bottom
	if ([cell.type isEqualToString:empty]) {
		return UITableViewCellEditingStyleNone;
	} else {
		return UITableViewCellEditingStyleDelete;
	}
	
}

// Set the editing state of the view controller. We pass this down to the table view and also modify the content
// of the table to insert a placeholder row for adding content when in editing mode.
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    [super setEditing:editing animated:animated];
	
    [self.contactDetailTable beginUpdates];
	
	NSArray *indexPaths = [NSArray arrayWithObjects:
    					   [NSIndexPath indexPathForRow:[self sectionCount:0] inSection:0],
    					   [NSIndexPath indexPathForRow:[self sectionCount:1] inSection:1],
    					   [NSIndexPath indexPathForRow:[self sectionCount:2] inSection:2],
    					   [NSIndexPath indexPathForRow:[self sectionCount:3] inSection:3],
    					   [NSIndexPath indexPathForRow:[self sectionCount:4] inSection:4],
    					   [NSIndexPath indexPathForRow:[self sectionCount:5] inSection:5],
    					   [NSIndexPath indexPathForRow:[self sectionCount:6] inSection:6],
    					   [NSIndexPath indexPathForRow:[self sectionCount:7] inSection:7],
    					   [NSIndexPath indexPathForRow:[self sectionCount:8] inSection:8],
    					   [NSIndexPath indexPathForRow:[self sectionCount:9] inSection:9],
						   nil];
	
    [self.contactDetailTable setEditing:editing animated:YES];
		
    if (editing) {
        // Show the placeholder rows
        [self.contactDetailTable insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
    } else {
        // Hide the placeholder rows.  We can actually get by without this.
        // [self.contactDetailTable deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
		// The solution below crashes, too.
		// NSMutableArray *theArray = [[NSMutableArray alloc] initWithCapacity:10];
		// NSIndexPath *aPath;
		
		// for (int y=0; y<10; y++) {
		//	for(int i=0;i<[self sectionCount:y];i++) {
		//		aPath = [NSIndexPath indexPathForRow:i inSection:y];
		//		if([[self.contactDetailTable indexPathsForVisibleRows] containsObject:aPath])
		//			[theArray addObject:aPath];
		//	}
		//}
        //[self.contactDetailTable deleteRowsAtIndexPaths:theArray withRowAnimation:UITableViewRowAnimationTop];
    }	
    [contactDetailTable endUpdates];
}

// delete personal phone cell
-(void)deletePersonalPhoneCell:(int)pIndex {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = YES;
	
	ContactCell*cell = [self.personalPhoneCells objectAtIndex:pIndex];

	if ([cell.type isEqualToString:@"p"]) {
		// Issue delete to cliqset
		NSMutableString* strTag = (NSMutableString*)[empty stringByAppendingFormat:@"%@", [cell.label isEqualToString:@"Home"] ? @"Personal" : cell.label];
		strTag = [strTag isEqualToString:@"Personal"] ? strTag : (NSMutableString*)[empty stringByAppendingFormat:@"%@%@", @"Personal", strTag];
		
		[myApp.cliqset deleteUserPhone:contact.contactIdentifier tag:strTag];
		// Remove from internal contact record
		[contact.phones removeObjectAtIndex:cell.elementIndex];
	}

	[self.contactDetailTable reloadData];
}	

// delete professional phone cell
-(void)deleteProfessionalPhoneCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = NO;
	
	ContactCell*cell = [self.professionalPhoneCells objectAtIndex:pIndex];
	
	if ([cell.type isEqualToString:@"p"]) {
		// Issue delete to cliqset
		NSMutableString* strTag = (NSMutableString*)[empty stringByAppendingFormat:@"%@", [cell.label isEqualToString:@"Office"] ? @"Work" : cell.label];
		strTag = [strTag isEqualToString:@"Work"] ? strTag : (NSMutableString*)[empty stringByAppendingFormat:@"%@%@", @"Work", strTag];
		
		[myApp.cliqset deleteUserPhone:contact.contactIdentifier tag:strTag];
		// Remove from internal contact record
		[contact.phones removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete personal email cell
-(void)deletePersonalEmailCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = YES;
	
	ContactCell*cell = [self.personalEmailCells objectAtIndex:pIndex];
	if ([cell.type isEqualToString:@"e"]) {
		// Issue delete to cliqset
		[myApp.cliqset deleteUserEmail:contact.contactIdentifier tag:@"Personal"];
		// Remove from internal contact record
		[contact.emailAddresses removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete professional email cell
-(void)deleteProfessionalEmailCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = NO;
	
	ContactCell*cell = [self.professionalEmailCells objectAtIndex:pIndex];
	if ([cell.type isEqualToString:@"e"]) {
		// Issue delete to cliqset
		[myApp.cliqset deleteUserEmail:contact.contactIdentifier tag:@"Work"];
		// Remove from internal contact record
		[contact.emailAddresses removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete personal url cell
-(void)deletePersonalURLCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = YES;
	
	ContactCell*cell = [self.personalURLCells objectAtIndex:pIndex];
	if ([cell.type isEqualToString:@"u"]) {
		// Issue delete to cliqset
		NSMutableString* strTag = (NSMutableString*)[empty stringByAppendingFormat:@"Personal%@", cell.label];		
		[myApp.cliqset deleteUserURL:contact.contactIdentifier tag:strTag];
		// Remove from internal contact record
		[contact.urls removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete professional url cell
-(void)deleteProfessionalURLCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = NO;
	
	ContactCell*cell = [self.professionalURLCells objectAtIndex:pIndex];
	if ([cell.type isEqualToString:@"u"]) {
		// Issue delete to cliqset
		NSMutableString* strTag = (NSMutableString*)[empty stringByAppendingFormat:@"Work%@", cell.label];		
		[myApp.cliqset deleteUserURL:contact.contactIdentifier tag:strTag];
		// Remove from internal contact record
		[contact.urls removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete personal im cell
-(void)deletePersonalIMCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = YES;
	
	ContactCell*cell = [self.personalIMCells objectAtIndex:pIndex];
	if ([cell.type isEqualToString:@"i"]) {
		// Issue delete to cliqset
		NSMutableString* strTag = (NSMutableString*)[empty stringByAppendingFormat:@"Personal%@", cell.label];		
		[myApp.cliqset deleteUserIM:contact.contactIdentifier tag:strTag];
		// Remove from internal contact record
		[contact.imScreenNames removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete professional im cell
-(void)deleteProfessionalIMCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = NO;
	
	ContactCell*cell = [self.professionalIMCells objectAtIndex:pIndex];
	if ([cell.type isEqualToString:@"i"]) {
		// Issue delete to cliqset
		NSMutableString* strTag = (NSMutableString*)[empty stringByAppendingFormat:@"Work%@", cell.label];		
		[myApp.cliqset deleteUserIM:contact.contactIdentifier tag:strTag];
		// Remove from internal contact record
		[contact.imScreenNames removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}	

// delete personal address cell
-(void)deletePersonalAddressCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = YES;
	
	ContactCell*cell = [self.personalAddressCells objectAtIndex:pIndex];	
	if ([cell.type isEqualToString:@"a"]) {
		// Issue delete to cliqset
		[myApp.cliqset deleteUserAddress:contact.contactIdentifier tag:@"Home"];
		// Remove from internal contact record
		[contact.addresses removeObjectAtIndex:cell.elementIndex];
	}
		
	[self.contactDetailTable reloadData];
}

// delete professional address cell
-(void)deleteProfessionalAddressCell:(int)pIndex {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.index>=0) {
		if (self.isFavorite) {
			// Dereference our contact
			for (int x=0; x<[myApp.contacts count]; x++) {
				Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
				
				if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:index]]) {
					contact = localContact;
					break;
				}
			}
		} 
		else {
			contact = (Contact *)[myApp.contacts objectAtIndex:self.index];
		}
	}	
	else {
		contact = bufferContact;
	}
	
	self.isPersonal = NO;
	
	ContactCell*cell = [self.professionalAddressCells objectAtIndex:pIndex];	
	if ([cell.type isEqualToString:@"a"]) {
		// Issue delete to cliqset
		[myApp.cliqset deleteUserAddress:contact.contactIdentifier tag:@"Work"];
		// Remove from internal contact record
		[contact.addresses removeObjectAtIndex:cell.elementIndex];
	}
	
	[self.contactDetailTable reloadData];
}

// Update the data model according to edit actions delete or insert.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
	NSLog(@"commitEditingStyle");
	
	// We have a delete going on?
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		//UITableViewCell * myCell = [aTableView cellForRowAtIndexPath:indexPath];
		switch (indexPath.section) {
			case 0:
				[self deletePersonalPhoneCell: indexPath.row];
				break;
			case 1:
				[self deletePersonalEmailCell: indexPath.row];
				break;
			case 2:
				[self deletePersonalURLCell: indexPath.row];
				break;
			case 3:
				[self deletePersonalIMCell: indexPath.row];
				break;
			case 4:
				[self deletePersonalAddressCell: indexPath.row];
				break;
			case 5:
				[self deleteProfessionalPhoneCell: indexPath.row];
				break;
			case 6:
				[self deleteProfessionalEmailCell: indexPath.row];
				break;
			case 7:
				[self deleteProfessionalURLCell: indexPath.row];
				break;
			case 8:
				[self deleteProfessionalIMCell: indexPath.row];
				break;
			case 9:
				[self deleteProfessionalAddressCell: indexPath.row];
				break;
			}
		}
	else {
		[self tableView:aTableView didSelectRowAtIndexPath:indexPath];	
		}
	
}

- (void)dealloc {
	[editButton release];
	[saveButton release];
	[cancelButton release];
	[header release];
	[footer release];
	[viewTimer release];
	[bufferContact release];
	[myName release];
	[myJob release];
	[deleteContactBtn release];
	[editUserBtn release];
	[addToFavesBtn release];	
	[personalPhoneCells release];
	[personalEmailCells release];
	[personalURLCells release];
	[personalIMCells release];
	[personalAddressCells release];
	[professionalPhoneCells release];
	[professionalEmailCells release];
	[professionalURLCells release];
	[professionalIMCells release];
	[professionalAddressCells release];

	[contactDetailTable release];
    [super dealloc];
}


@end

// My contact cells (personal and professional)
// This is used to build the personal / professional sections of the table
@implementation ContactCell

@synthesize label        = _label;
@synthesize content      = _content;
@synthesize type         = _type;
@synthesize tag          = _tag;
@synthesize elementIndex = _elementIndex;

-(id) init {	
	self = [super init];
	return self;
}

-(NSString*)description {
	NSMutableString * desc = (NSMutableString*)[@"" stringByAppendingFormat:@"\r\nContactCell Object\r\n__________________\r\nlabel: %@\r\ncontent: %@\r\ntype: %@\r\ntag: %d", self.label, self.content, self.type, self.tag];
	return desc;
}

-(void)dealloc {
	
	// NSLog(@"%@", [self description]);
	
	[_type release];
	[_label release];
	[_content release];	
	[super dealloc];
}

@end

